<?php

namespace backend\controllers;

use Yii;
use common\models\projectmoney\ProjectMoney;
use common\models\projectmoney\ProjectMoneySearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;

/**
 * ProjectMoneyController implements the CRUD actions for ProjectMoney model.
 */
class ProjectMoneyController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ProjectMoney models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ProjectMoneySearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ProjectMoney model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ProjectMoney model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate($cid)
    {
        
        $model = new ProjectMoney();

        if ($model->load(Yii::$app->request->post())) {
            
            $transaction = \Yii::$app->db->beginTransaction();
            try {
            
                foreach ($model->name as $k=>$vo) {
                    
                    Yii::$app->db->createCommand()->insert('project_money', [
                        'name' => $vo,
                        'pr_id' => $cid,
                    ])->execute();
                }
                
                $transaction->commit();
                Yii::$app->getSession()->setFlash('success', '新增成功');
                return $this->redirect(['project-paid/index', 'id' => $cid]);
                
            } catch (\Exception $e) {
                
                $transaction->rollBack();
                $remark = $e->getMessage();
                Yii::$app->getSession()->setFlash('error', $remark);

                return $this->render('create', [
                    'model' => $model,
                ]);
            }       
                
                
                
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ProjectMoney model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($cid)
    {
        $arr = ArrayHelper::map(ProjectMoney::find()->where(['pr_id' => $cid])->all(), 'id', 'name');
        $post = Yii::$app->request->post()['ProjectMoney'];

        if (Yii::$app->request->post()) {

            $transaction = \Yii::$app->db->beginTransaction();
            try {

                foreach (Yii::$app->request->post()['ProjectMoney']['name'] as $k=>$vo) {
                    if (in_array($vo, $arr)) {
                        
                        Yii::$app->db->createCommand()->update('project_money', ['initial_cash' => $post['initial_cash'][$k], 'total_expenditure' => $post['total_expenditure'][$k], 'residual_cash' => $post['residual_cash'][$k]], ['name' => $vo, 'pr_id' => $cid])->execute();
                        
                    } else {
                        
                        Yii::$app->db->createCommand()->insert('project_money', [
                            'initial_cash' => $post['initial_cash'][$k],
                            'total_expenditure' => $post['total_expenditure'][$k],
                            'residual_cash' => $post['residual_cash'][$k],
                            'name' => $vo,
                            'pr_id' => $cid,
                        ])->execute();
    
                    }
                }
            
                Yii::$app->getSession()->setFlash('success', '更新成功');
                return $this->redirect(['/project-paid/index', 'id' => $cid]);
            } catch (\Exception $e) {
                
                $transaction->rollBack();
                $remark = $e->getMessage();
                Yii::$app->getSession()->setFlash('error', $remark);
                return $this->redirect(['/project-paid/index', 'id' => $cid]);
            }       
        }
    }

    /**
     * Deletes an existing ProjectMoney model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ProjectMoney model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ProjectMoney the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ProjectMoney::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
